package org.hagopa.games.moneypool.dblayer.Connector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConnector {
	private static String driver = "com.mysql.jdbc.Driver";
	private static String jdbcUrl = "jdbc:mysql://localhost/bogo";
	private static String user = "root";
	private static String password = "";
	
	private static Connection conn = null;
	private static boolean isConnected = false;
	private static boolean wasSetUp = false;
	private ResultSet rs = null;
	
	
	private static DBConnector instance = new DBConnector();
	
	public DBConnector()
	{
		System.out.println("DBConnector Created");
	}
	
	public static DBConnector getInstance()
	{
		if(null == instance)
		{
			instance = new DBConnector();
		}
		
		return instance;
	}
	public static void setInitialSettings(String host,String usr, String pwd, String dbname)
	{
		if(wasSetUp == false)
		{
			System.out.println("DBNAME : " + dbname);
			jdbcUrl = "jdbc:mysql://"+ host + "/" + dbname;
			user = usr;
			password = pwd;
			wasSetUp = true;
		}
	}
	public static boolean isConnected()
	{
		if(isConnected == false)
		{
			System.out.println("DB Connection failure");
		}
		return isConnected;
	}
	public static boolean connect()
	{
		try {
			Class.forName(DBConnector.driver).newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isConnected = false;
			return false;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(jdbcUrl, user, password);
			isConnected = true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isConnected = false;
			return false;
		}
		return true;
	}
	
	
	
	
	public static void disconnect()
	{
		try {
			conn.close();
			isConnected = false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isConnected = false;
		}
	}
	public static Connection getConn() {
		return conn;
	}
	public void setConn(Connection connect) {
		conn = connect;
	}
	public ResultSet getRs() {
		return rs;
	}
	public void setRs(ResultSet rs) {
		this.rs = rs;
	}
}
